import React from 'react'
import moment from 'moment';
import ReactDOM from 'react-dom';
import {
    List,
    Card,
    Row,
    Col,
    Radio,
    Input,
    Progress,
    Button,
    Icon,
    Dropdown,
    Menu,
    Avatar,
    Modal,
    Form,
    DatePicker,
    Select,
    notification,
} from 'antd';
import styles from './Manage.less';
import Result from '@/components/Result';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {connect} from "react-redux";
import {FETCH_DEVICES, REFRESH_DEVICES} from "../../models/device/const";
import {createDevice, deleteDevice, updateDevice} from "../../services/device";
import {OFFLINE, ONLINE, RUNNING} from "../../config/const";
import MyDeviceTypeSelect from "../../components/MyDeviceTypeSelect";
import getDeviceList from "../../models/selectors";


const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const {Option} = Select;


// @connect(({device}) => ({
//   deviceList: getDeviceList(device),
// }))
@connect(function ({device}) {
    return {
        deviceList:getDeviceList(device)
    }
})


@Form.create()
class DeviceSetting extends React.PureComponent {
    state = {
        visible: false,
        done: false,
        sort: 1,
        status: -1,
        current: null,
    };

    formLayout = {
        labelCol: {span: 7},
        wrapperCol: {span: 13},
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: FETCH_DEVICES,
        });
    }

    showModal = () => {
        this.setState({
            visible: true,
            current: undefined,
        });
    };

    showEditModal = item => {
        this.setState({
            visible: true,
            current: item,
        });
    };

    handleDone = () => {
        // setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            done: false,
            visible: false,
        });
    };

    handleCancel = () => {
        // setTimeout(() => this.addBtn.blur(), 0);
        this.setState({
            visible: false,
        });
    };

    handleUpdateDevice = async (device_id, fieldsValue) => {
        const rsp = await updateDevice(device_id, fieldsValue);
        if (rsp.status === 'OK') {
            const {dispatch} = this.props;
            dispatch({
                type: REFRESH_DEVICES,
            });
            this.setState({
                done: true,
            });
        } else {
            this.setState({visible: false, done: false})
        }
    };
    handleCreateDevice = async (fieldsValue) => {
        const rsp = await createDevice(fieldsValue);
        if (rsp.statusCode === 201) {
            const {dispatch} = this.props;
            dispatch({
                type: REFRESH_DEVICES,
            });
            this.setState({
                done: true,
            });
        } else {
            this.setState({visible: false, done: false});
            notification.error({
                message: `创建失败`,
                description: JSON.stringify(rsp.data),
                duration: 5,
            });
        }
    };

    handleSubmit = e => {
        e.preventDefault();
        const {form} = this.props;
        const {current} = this.state;
        const device_id = current ? current.device_id : '';

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            this.handleUpdateDevice(device_id, fieldsValue)
        });
    };

    handleAddDevice = e => {
        e.preventDefault();
        const {form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            this.handleCreateDevice(fieldsValue)
        });
    };

    deleteItem = async id => {
        const {dispatch} = this.props;
        const rsp = await deleteDevice(id);
        if (rsp.statusCode === 204) {
            notification.info({
                message: `删除成功`,
                duration: 5,
            });
            dispatch({
                type: REFRESH_DEVICES
            })
        } else {
            notification.error({
                message: `删除失败`,
                description: JSON.stringify(rsp.data),
                duration: 5,
            });
        }
    };

    handleSortChange = (e) => {
        const sort = e.target.value;
        this.setState({sort})
    };

    handleClassChange = (e) => {
        const status = e.target.value;
        this.setState({status})
    };

    render() {
        const getModalContent = (current) => {
            if (done) {
                return (
                    <Result
                        type="success"
                        title="操作成功"
                        // description="一系列的信息描述，很短同样也可以带标点。"
                        actions={
                            <Button type="primary" onClick={this.handleDone}>
                                知道了
                            </Button>
                        }
                        className={styles.formResult}
                    />
                );
            }
            if (current) return (
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="设备名称" {...this.formLayout}>
                        {getFieldDecorator('nickname', {
                            // rules: [{required: true, message: '请输入任务名称'}],
                            initialValue: current.nickname,
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="设备描述" {...this.formLayout}>
                        {getFieldDecorator('desc', {
                            initialValue: current.desc,
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="设备分类" {...this.formLayout}>
                        {getFieldDecorator('type', {
                            initialValue: '0',
                            rules: [{required: true, message: '请选择设备分类'}],
                        })(<Select>
                            <Option value="0">一期</Option>
                            <Option value="1">二期</Option>
                        </Select>)}
                    </FormItem>
                </Form>
            );

            return (
                <Form onSubmit={this.handleAddDevice}>
                    <FormItem label="设备编号" {...this.formLayout}>
                        {getFieldDecorator('id', {
                            rules: [{required: true, message: '请输入设备编号'}],
                        })(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="设备名称" {...this.formLayout}>
                        {getFieldDecorator('nickname', {})(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="设备描述" {...this.formLayout}>
                        {getFieldDecorator('desc', {})(<Input placeholder="请输入"/>)}
                    </FormItem>
                    <FormItem label="设备分类" {...this.formLayout}>
                        {getFieldDecorator('type', {
                            initialValue: '0',
                            rules: [{required: true, message: '请选择设备分类'}],
                        })(<Select>
                            <Option value="0">一期</Option>
                            <Option value="1">二期</Option>
                        </Select>)}
                    </FormItem>
                </Form>
            )
        };

        const {
            form: {getFieldDecorator},
            deviceList,
        } = this.props;
      if (!deviceList) return null;
      const {visible, done, current, sort, status} = this.state;
        const loading = false;
        const editAndDelete = (key, currentItem) => {
            if (key === 'edit') this.showEditModal(currentItem);
            else if (key === 'delete') {
                Modal.confirm({
                    // title: '删除任务',
                    content: '确定删除该设备吗？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => this.deleteItem(currentItem.device_id),
                });
            }
        };

        const modalFooter = done
            ? {footer: null, onCancel: this.handleDone}
            : {okText: '保存', onOk: current ? this.handleSubmit : this.handleAddDevice, onCancel: this.handleCancel};

        const ListContent = ({
                                 data: {
                                     last_battery,
                                     battery_life,
                                     device_id,
                                     nickname,
                                     icon,
                                     record_time,
                                     last_record_lng,
                                     last_record_lat,
                                     last_record_time,
                                 }
                             }) => (
            <div className={styles.listContent}>
                <div className={styles.listContentItem}>
                    <span>设备名称</span>
                    <p>{nickname}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>最后坐标</span>
                    <p>{last_record_lng / 1e6}, {last_record_lat / 1e6}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>最后上报时间</span>
                    <p>{last_record_time ? moment(last_record_time * 1e3).format('YYYY-MM-DD HH:mm:ss') : '00:00:00'}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>开始时间</span>
                    <p>{record_time.slice(0, 10)}</p>
                </div>
                <div className={styles.listContentItem}>
                    <span>剩余电量%</span>
                    <p>{last_battery || 0}</p>
                </div>
                {/*<div className={styles.listContentItem}>*/}
                {/*<span>预计续航时间</span>*/}
                {/*<p>{battery_life}</p>*/}
                {/*</div>*/}
            </div>
        );

        const getData = (data) => {
            if (status !== -1) data = data.filter(item => item.status === status);
            return data.sort((a, b) => sort * (a.device_id - b.device_id))
        };


        const statusMap = deviceList.reduce((obj, item) => (++obj[item.status], obj), {
            [OFFLINE]: 0,
            [ONLINE]: 0,
            [RUNNING]: 0,
        });

        return (
            <PageHeaderWrapper>
                <div className={styles.standardList}>
                    <Card
                      className={styles.listCard}
                      bordered={false}
                      title={<div>
                        设备管理
                        <MyDeviceTypeSelect/>
                      </div>}
                      style={{marginTop: 24}}
                      bodyStyle={{padding: '0 32px 40px 32px'}}
                      extra={<Button onClick={this.showModal} type="primary" shape="circle" icon="plus"/>}
                    >


                        <div style={{float: 'left'}}>
                            状态:
                            <RadioGroup defaultValue="-1" onChange={this.handleClassChange}>
                                <RadioButton value="-1">全部</RadioButton>
                                <RadioButton value={RUNNING}>行驶中 {statusMap[RUNNING]}</RadioButton>
                                <RadioButton value={ONLINE}>停驻 {statusMap[ONLINE]}</RadioButton>
                                <RadioButton value={OFFLINE}>离线 {statusMap[OFFLINE]}</RadioButton>
                            </RadioGroup>
                        </div>
                        <div style={{float: 'right'}}>
                            <Radio.Group defaultValue="1" onChange={this.handleSortChange}>
                                <Radio.Button value="1"><Icon type="up"/> 升序排列</Radio.Button>
                                <Radio.Button value="-1">降序排列 <Icon type="down"/></Radio.Button>
                            </Radio.Group>
                        </div>
                        <div style={{clear: 'both', margin: '40px 0'}}/>
                        <List
                            size="large"
                            rowKey="id"
                            loading={loading}
                            pagination={true}
                            dataSource={getData(deviceList)}
                            renderItem={item => (
                                <List.Item
                                    actions={[
                                        <a
                                            onClick={e => {
                                                e.preventDefault();
                                                editAndDelete('edit', item);
                                            }}
                                        >编辑
                                        </a>,
                                        <a onClick={e => {
                                            e.preventDefault();
                                            editAndDelete('delete', item);
                                        }}>删除</a>
                                        ,
                                    ]}
                                >
                                    <List.Item.Meta
                                        // avatar={<Avatar src={item.logo} shape="square" size="large"/>}
                                        title={<span>设备编号: {item.device_id}</span>}
                                        description={<span>{item.desc}</span>}
                                    />
                                    <ListContent data={item}/>
                                </List.Item>
                            )}
                        />
                    </Card>
                </div>
                <Modal
                    title={done ? null : `设备${current ? '编辑' : '添加'}`}
                    className={styles.standardListForm}
                    width={640}
                    bodyStyle={done ? {padding: '72px 0'} : {padding: '28px 0 0'}}
                    destroyOnClose
                    visible={visible}
                    {...modalFooter}
                >
                    {getModalContent(current)}
                </Modal>
            </PageHeaderWrapper>
        );
    }
}

export default DeviceSetting;
